package chooongg.base.utils

import android.Manifest.permission.WRITE_SETTINGS
import android.provider.Settings
import android.provider.Settings.SettingNotFoundException
import android.view.Window
import androidx.annotation.IntRange
import androidx.annotation.RequiresPermission
import chooongg.base.Utils

/**
 * 亮度工具类
 */
object BrightnessUtils {

    /**
     * 是否启用自动亮度
     */
    fun isAutoBrightnessEnabled(): Boolean {
        return try {
            val mode = Settings.System.getInt(
                Utils.app.contentResolver,
                Settings.System.SCREEN_BRIGHTNESS_MODE
            )
            mode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC
        } catch (e: Settings.SettingNotFoundException) {
            e.printStackTrace()
            false
        }
    }

    /**
     * 设置是否启用自动亮度
     */
    fun setAutoBrightnessEnabled(enabled: Boolean): Boolean {
        return Settings.System.putInt(
            Utils.app.contentResolver,
            Settings.System.SCREEN_BRIGHTNESS_MODE,
            if (enabled) Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC else Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL
        )
    }

    /**
     * 获取屏幕亮度
     * @return 0-255
     */
    fun getBrightness(): Int {
        return try {
            Settings.System.getInt(Utils.app.contentResolver, Settings.System.SCREEN_BRIGHTNESS)
        } catch (e: SettingNotFoundException) {
            e.printStackTrace()
            0
        }
    }

    /**
     * 设置屏幕亮度
     */
    @RequiresPermission(WRITE_SETTINGS)
    fun setBrightness(@IntRange(from = 0, to = 255) brightness: Int): Boolean {
        val resolver = Utils.app.contentResolver
        val b = Settings.System.putInt(resolver, Settings.System.SCREEN_BRIGHTNESS, brightness)
        resolver.notifyChange(Settings.System.getUriFor("screen_brightness"), null)
        return b
    }

    /**
     * 设置窗口亮度
     */
    fun setWindowBrightness(window: Window, @IntRange(from = 0, to = 255) brightness: Int) {
        val lp = window.attributes
        lp.screenBrightness = brightness / 255f
        window.attributes = lp
    }

    /**
     * 获取窗口亮度
     */
    fun getWindowBrightness(window: Window): Int {
        val lp = window.attributes
        val brightness = lp.screenBrightness
        return if (brightness < 0) getBrightness() else (brightness * 255).toInt()
    }
}